#启动mongo集群
docker stack deploy -c /home/mongo/mongo-stack.yml mongo

#初始化 Mongo 配置集群
docker exec -it $(docker ps | grep "mongors-cfg1" | awk '{ print $1 }') bash\
    -c "echo 'rs.initiate({_id: \"cfgrs\",configsvr: true, members: \
    [{ _id : 0, host : \"mongors-cfg1\" },{ _id : 1, host : \"mongors-cfg2\" },\
    { _id : 2, host : \"mongors-cfg3\" }]})' | mongo"

#初始化三个 Mongo 数据集群
docker exec -it $(docker ps | grep "mongors-primary1" | awk '{ print $1 }') \
    bash -c "echo 'rs.initiate({_id : \"shard1\", members:\
    [{ _id : 0, host : \"mongors-primary1\" },{ _id : 1, host : \"mongors-secondary1\" },\
    { _id : 2, host : \"mongors-arbitor1\", arbiterOnly: true }]})' | mongo"

docker exec -it $(docker ps | grep "mongors-primary2" | awk '{ print $1 }') \
    bash -c "echo 'rs.initiate({_id : \"shard2\", members:\
    [{ _id : 0, host : \"mongors-primary2\" },{ _id : 1, host : \"mongors-secondary2\" },\
    { _id : 2, host : \"mongors-arbitor2\", arbiterOnly: true }]})' | mongo"

docker exec -it $(docker ps | grep "mongors-primary3" | awk '{ print $1 }') \
    bash -c "echo 'rs.initiate({_id : \"shard3\", members:\
    [{ _id : 0, host : \"mongors-primary3\" },{ _id : 1, host : \"mongors-secondary3\" },\
    { _id : 2, host : \"mongors-arbitor3\", arbiterOnly: true }]})' | mongo"


#将三个数据集群当做分片加入 mongos
docker exec -it $(docker ps | grep "mongors-router" | awk '{ print $1 }') bash -c\
    "echo 'sh.addShard(\"shard1/mongors-primary1:27017,mongors-secondary1:27017,mongors-arbitor1:27017\")' | mongo "

docker exec -it $(docker ps | grep "mongors-router" | awk '{ print $1 }') bash -c\
    "echo 'sh.addShard(\"shard2/mongors-primary2:27017,mongors-secondary2:27017,mongors-arbitor2:27017\")' | mongo "

docker exec -it $(docker ps | grep "mongors-router" | awk '{ print $1 }') bash -c\
    "echo 'sh.addShard(\"shard3/mongors-primary3:27017,mongors-secondary3:27017,mongors-arbitor3:27017\")' | mongo "


#选择任意的router设置用户
db.createUser({
    user: "root",
    pwd: "abcd.1234",
    roles: [
    {role: "clusterAdmin", db: "admin"},
    {role: "readWriteAnyDatabase", db: "admin"},
    {role: "userAdminAnyDatabase", db: "admin"},
    {role: "dbAdminAnyDatabase", db: "admin"}]
})